package com.lagou.edu.component;

import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @Author: yeqingyun
 * @Date: 2020/11/27 16:56
 */
@Component
@RefreshScope
public class EmailComponent {

    @Value("${email.serverAccount}")
    private String serverAccount = "qingyunye@foxmail.com";
    @Value("${email.serverPassword}")
    private String serverPassword = "vfezihrhdpnpbehi";

    @Async
    @SneakyThrows
    public void sendEmail(String receiverEmail, String message){
        Properties props = new Properties();
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", "smtp.qq.com");// smtp服务器地址

        Session session = Session.getInstance(props);
        session.setDebug(true);
        Message msg = new MimeMessage(session);
        msg.setSubject("拉钩验证码");
        msg.setText(message);
        msg.setFrom(new InternetAddress(serverAccount));//发件人邮箱(我的163邮箱)
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(receiverEmail)); //收件人邮箱(我的QQ邮箱)
        msg.saveChanges();

        Transport transport = session.getTransport();
        transport.connect(serverAccount, serverPassword);//发件人邮箱,授权码(可以在邮箱设置中获取到授权码的信息)
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
    }
}
